package cgs_worksheet

import (
	"fmt"
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/upload"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"
)

func init() {
	//server.Handle(http.MethodPost, "/api/Cgs/UploadExcel", UploadExcel,server.ImportExcel)
	server.Post("/api/Cgs/UploadExcel", UploadExcel, "上传excel文件", server.Login)
}

func UploadExcel(w http.ResponseWriter, r *http.Request) {
	_ = r.ParseMultipartForm(server.Config.Upload.MaxSize)
	files := r.MultipartForm.File

	// 权限
	if server.Config.Authority.Enabled {
		user, _ := server.GetCurrentUser(r)

		if user == nil {
			_, _ = helper.WriteJSON(w, server.CgsResult{
				Code: 300,
				Msg:  "Permission denied.",
			})
			return
		}

	}

	// check uploaded file
	if len(files) != 1 {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  "Please select an file.",
		})
		return
	}

	file := files["file"][0]
	fileName := file.Filename
	fileSize := file.Size
	fileType := file.Header.Get("Content-Type")
	fileExt := filepath.Ext(fileName)
	fileNameWithoutExt := strings.TrimSuffix(fileName, fileExt)

	if strings.ToLower(fileExt) != ".xls" &&
		strings.ToLower(fileExt) != ".xlsx" {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  "Only xls, xlsx format is allowed to upload!",
		})
		return
	}

	// save file
	now := time.Now()
	pinyin := helper.ConvertToPinYin(fileNameWithoutExt)
	fmt.Printf("%+v", pinyin)
	fileName = pinyin.TotalPinYin + helper.TimeToString(now, "yyyyMMddHH") + fileExt


	savePath := fmt.Sprintf("/Upload/Excel/%v", helper.TimeToString(now, "yyyyMMddHH"))
	physicalPath := server.MapPath(savePath)

	if _, err := os.Stat(physicalPath); os.IsNotExist(err) {
		_ = os.MkdirAll(physicalPath, 0755)
	}

	targetPath := fmt.Sprintf("%v/%v", physicalPath, fileName)
	target, err := os.Create(targetPath)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	defer target.Close()

	source, err := file.Open()
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	defer source.Close()

	_, _ = io.Copy(target, source)

	url := fmt.Sprintf("%v/%v", savePath, fileName)

	_, _ = helper.WriteJSON(w, server.CgsResult{
		Code: 200,
		Msg:  "Upload successfully!",
		Data: upload.FileData{FileName: fileName, FileSize: fileSize, FileType: fileType, URL: url},
	})
}

